import React, { useState, useEffect } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { 
  LockClosedIcon,
  EyeIcon,
  EyeSlashIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  ShieldCheckIcon
} from '@heroicons/react/24/outline'
import { Card, Button, Input } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'
import { authService } from '@/services/api/authService'

const resetPasswordSchema = z.object({
  password: z.string()
    .min(8, 'Password must be at least 8 characters')
    .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, 'Password must contain at least one uppercase letter, one lowercase letter, and one number'),
  confirmPassword: z.string()
}).refine((data) => data.password === data.confirmPassword, {
  message: "Passwords don't match",
  path: ["confirmPassword"],
})

type ResetPasswordFormData = z.infer<typeof resetPasswordSchema>

export const ResetPasswordPage: React.FC = () => {
  const [searchParams] = useSearchParams()
  const [isLoading, setIsLoading] = useState(false)
  const [isSuccess, setIsSuccess] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [tokenValid, setTokenValid] = useState<boolean | null>(null)

  const token = searchParams.get('token')

  const {
    register,
    handleSubmit,
    formState: { errors },
    watch
  } = useForm<ResetPasswordFormData>({
    resolver: zodResolver(resetPasswordSchema)
  })

  const password = watch('password')

  useEffect(() => {
    // Validate token on component mount
    if (!token) {
      setTokenValid(false)
      setError('Invalid or missing reset token')
    } else {
      setTokenValid(true)
    }
  }, [token])

  const onSubmit = async (data: ResetPasswordFormData) => {
    if (!token) {
      setError('Invalid reset token')
      return
    }

    setIsLoading(true)
    setError(null)

    try {
      await authService.resetPassword(token, data.password)
      setIsSuccess(true)
    } catch (error: any) {
      setError(error.response?.data?.error?.message || 'Failed to reset password. Please try again.')
    } finally {
      setIsLoading(false)
    }
  }

  // Password strength indicator
  const getPasswordStrength = (password: string) => {
    if (!password) return { strength: 0, label: '', color: '' }
    
    let strength = 0
    if (password.length >= 8) strength++
    if (/[a-z]/.test(password)) strength++
    if (/[A-Z]/.test(password)) strength++
    if (/\d/.test(password)) strength++
    if (/[^a-zA-Z0-9]/.test(password)) strength++

    const labels = ['Very Weak', 'Weak', 'Fair', 'Good', 'Strong']
    const colors = ['bg-red-500', 'bg-orange-500', 'bg-yellow-500', 'bg-blue-500', 'bg-green-500']
    
    return {
      strength,
      label: labels[strength - 1] || '',
      color: colors[strength - 1] || 'bg-gray-300'
    }
  }

  const passwordStrength = getPasswordStrength(password || '')

  // Success state
  if (isSuccess) {
    return (
      <ErrorBoundary>
        <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
          <div className="max-w-md w-full">
            <Card className="p-8 text-center">
              <div className="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-6">
                <CheckCircleIcon className="h-8 w-8 text-green-600" />
              </div>

              <h2 className="text-2xl font-bold text-gray-900 mb-4">
                Password reset successful!
              </h2>

              <p className="text-gray-600 mb-6">
                Your password has been successfully reset. You can now sign in with your new password.
              </p>

              <Button
                as={Link}
                to="/auth/login"
                variant="primary"
                fullWidth
                size="lg"
              >
                Continue to Sign In
              </Button>
            </Card>
          </div>
        </div>
      </ErrorBoundary>
    )
  }

  // Invalid token state
  if (tokenValid === false) {
    return (
      <ErrorBoundary>
        <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
          <div className="max-w-md w-full">
            <Card className="p-8 text-center">
              <div className="mx-auto w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mb-6">
                <ExclamationTriangleIcon className="h-8 w-8 text-red-600" />
              </div>

              <h2 className="text-2xl font-bold text-gray-900 mb-4">
                Invalid reset link
              </h2>

              <p className="text-gray-600 mb-6">
                This password reset link is invalid or has expired. Please request a new one.
              </p>

              <div className="space-y-3">
                <Button
                  as={Link}
                  to="/auth/forgot-password"
                  variant="primary"
                  fullWidth
                >
                  Request New Reset Link
                </Button>
                <Button
                  as={Link}
                  to="/auth/login"
                  variant="outline"
                  fullWidth
                >
                  Back to Sign In
                </Button>
              </div>
            </Card>
          </div>
        </div>
      </ErrorBoundary>
    )
  }

  return (
    <ErrorBoundary>
      <div className="min-h-screen flex">
        {/* Left Side - Branding */}
        <div className="hidden lg:flex lg:w-1/2 bg-gradient-to-br from-purple-600 to-pink-700 relative overflow-hidden">
          <div className="absolute inset-0 bg-black opacity-20"></div>
          <div className="relative z-10 flex flex-col justify-center px-12 text-white">
            <div className="mb-8">
              <div className="flex items-center space-x-3 mb-6">
                <div className="p-3 bg-white bg-opacity-20 rounded-lg">
                  <ShieldCheckIcon className="h-8 w-8" />
                </div>
                <h1 className="text-3xl font-bold">Secure Reset</h1>
              </div>
              <h2 className="text-4xl font-bold mb-4">
                Create a new password
              </h2>
              <p className="text-xl text-purple-100 leading-relaxed">
                Choose a strong password to keep your account secure.
              </p>
            </div>
            
            <div className="space-y-4">
              <div className="flex items-center space-x-3">
                <CheckCircleIcon className="w-6 h-6 text-purple-300" />
                <span className="text-purple-100">Secure encryption</span>
              </div>
              <div className="flex items-center space-x-3">
                <CheckCircleIcon className="w-6 h-6 text-purple-300" />
                <span className="text-purple-100">Password strength validation</span>
              </div>
              <div className="flex items-center space-x-3">
                <CheckCircleIcon className="w-6 h-6 text-purple-300" />
                <span className="text-purple-100">Immediate access after reset</span>
              </div>
            </div>
          </div>
        </div>

        {/* Right Side - Reset Form */}
        <div className="flex-1 flex items-center justify-center px-4 sm:px-6 lg:px-8 bg-gray-50">
          <div className="max-w-md w-full">
            <Card className="p-8">
              <div className="text-center mb-8">
                <div className="mx-auto w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mb-4">
                  <LockClosedIcon className="h-8 w-8 text-purple-600" />
                </div>
                <h2 className="text-2xl font-bold text-gray-900">Reset your password</h2>
                <p className="mt-2 text-sm text-gray-600">
                  Enter your new password below
                </p>
              </div>

              <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                {error && (
                  <div className="flex items-center p-4 bg-red-50 border border-red-200 rounded-md">
                    <ExclamationTriangleIcon className="h-5 w-5 text-red-400 mr-3" />
                    <div className="text-sm text-red-700">{error}</div>
                  </div>
                )}

                <div>
                  <Input
                    label="New password"
                    type={showPassword ? 'text' : 'password'}
                    placeholder="Enter your new password"
                    leftIcon={<LockClosedIcon />}
                    rightIcon={
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="text-gray-400 hover:text-gray-600"
                      >
                        {showPassword ? <EyeSlashIcon className="h-5 w-5" /> : <EyeIcon className="h-5 w-5" />}
                      </button>
                    }
                    error={errors.password?.message}
                    {...register('password')}
                    fullWidth
                  />
                  
                  {/* Password Strength Indicator */}
                  {password && (
                    <div className="mt-2">
                      <div className="flex items-center justify-between text-xs text-gray-600 mb-1">
                        <span>Password strength</span>
                        <span className={`font-medium ${
                          passwordStrength.strength >= 4 ? 'text-green-600' : 
                          passwordStrength.strength >= 3 ? 'text-blue-600' :
                          passwordStrength.strength >= 2 ? 'text-yellow-600' : 'text-red-600'
                        }`}>
                          {passwordStrength.label}
                        </span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div 
                          className={`h-2 rounded-full transition-all duration-300 ${passwordStrength.color}`}
                          style={{ width: `${(passwordStrength.strength / 5) * 100}%` }}
                        />
                      </div>
                    </div>
                  )}
                </div>

                <Input
                  label="Confirm new password"
                  type={showConfirmPassword ? 'text' : 'password'}
                  placeholder="Confirm your new password"
                  leftIcon={<LockClosedIcon />}
                  rightIcon={
                    <button
                      type="button"
                      onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                      className="text-gray-400 hover:text-gray-600"
                    >
                      {showConfirmPassword ? <EyeSlashIcon className="h-5 w-5" /> : <EyeIcon className="h-5 w-5" />}
                    </button>
                  }
                  error={errors.confirmPassword?.message}
                  {...register('confirmPassword')}
                  fullWidth
                />

                <Button
                  type="submit"
                  loading={isLoading}
                  disabled={isLoading}
                  fullWidth
                  size="lg"
                >
                  Reset Password
                </Button>

                <div className="text-center">
                  <Link
                    to="/auth/login"
                    className="text-sm text-gray-600 hover:text-gray-900"
                  >
                    Back to Sign In
                  </Link>
                </div>
              </form>
            </Card>
          </div>
        </div>
      </div>
    </ErrorBoundary>
  )
}
